<?php

/**
 * 
 * @author littlexiang<littlexiang521@gmail.com>
 * @version    SVN: $Id: ShopModel.php 62 2009-07-22 04:45:58Z littlexiang521 $
 */
class ShopModel extends Model {
    protected $_table = 'shop';
    public function getShops ($line, $station_id, $tag_name, $order) {
        $q = 'SELECT s.*, a.title, a.location, a.start_time, a.end_time
       			FROM tag t, shoptag st, shop s
       			LEFT JOIN activity a
       			ON s.id = a.shop_id AND a.is_deleted = 0
       			WHERE s.is_deleted = 0
       			AND st.shop_id = s.id AND st.tag_id = t.id';
       	$q .= $tag_name ? ' AND t.name = ?': '';
        $q .= $station_id ? ' AND s.station_id = ?' : '';
        $q .= $line ? ' AND s.station_id IN (SELECT id FROM station WHERE line = ?)' : '';
        $q .= ' GROUP BY s.id';
        
        $q .= $order == 'time' ? ' ORDER BY s.update_time DESC' : '';
        $q .= $order == 'view' ? ' ORDER BY s.view_times DESC' : '';
        
        $array = array();
        if ($tag_name){
            $array[] = $tag_name;
        }
        if ($line){
            $array[] = $line;
        }elseif ($station_id){
            $array[] = $station_id;
        }
        
        return $this->fetchAll($q, $array);
    }
    
    public function getShopById ($id) {
        $q = 'SELECT s.*, st.id st_id, st.name st_name, st.line st_line
        		FROM shop s
        		LEFT JOIN station st
        		ON s.station_id = st.id
        		WHERE s.id = ? AND s.is_deleted = 0';
        return $this->fetch($q, array($id));
    }
    
    public function getShopTags ($id) {
        $q = 'SELECT tag.*
        		FROM shoptag, tag
        		WHERE shoptag.shop_id = ? AND tag.id = shoptag.tag_id';
        return $this->fetchAll($q, array($id));
    }
    
    public function getShopGoods ($id) {
        $q = 'SELECT *
        		FROM goods
        		WHERE shop_id = ? AND is_deleted = 0';
        return $this->fetchAll($q, array($id));
    }
    
    public function getShopComments ($id, $limit) {
        $q = "SELECT *
        		FROM comment
        		WHERE shop_id = ?
        		LIMIT $limit";
        return $this->fetchAll($q, array($id));
    }
    
    public function countShopComment ($id) {
        $q = 'SELECT COUNT(*) count
        		FROM comment 
        		WHERE shop_id = ?';
        return $this->fetch($q, array($id))->count;
    }
    
    public function viewPlus ($shopid) {
        $q = 'UPDATE shop
        		SET view_times = view_times+1
        		WHERE id = ?';
        return $this->execute($q, array($shopid));
    }
}